<?php
/**
 * Galdic project
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Galdic
 * @package    Galdic
 * @copyright  Copyright (c) 2009 vifito (http://vifito.eu)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * Model_Terms
 * 
 * @package    Galdic
 * @copyright  Copyright (c) 2009 vifito (http://vifito.eu)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Terms.php 1 2009-09-15 17:50:28Z vifito $
 */
class Model_Terms 
{
    protected $_db = null;
    
    public function __construct()
    {
        // Get Database adapter from Zend_Application
        $front = Zend_Controller_Front::getInstance();
        $container = $front->getParam('bootstrap')->getContainer();
        $this->_db = $container->db;
    }
    
    public function getDefinitions($q, $expand=true)
    {
        $q = strip_tags($q);
        $q = preg_replace('/[^a-z0-9_\-\.áéíóúüñç ]/i', '', $q);
        $q = trim($q);
        $q_sql = $q;
        
        if($expand) {
            $q_sql .= '%';
        }
        
        $sql = 'SELECT t.name, t.pronuntiation, d.* FROM terms t, definitions d WHERE t.name LIKE "' .
                $q_sql . '" AND t.id=d.term_id ORDER BY t.name, d.id LIMIT 0, 10';        
        
        $result = $this->_db->fetchAll($sql);
        
        $current = ''; $ptr = -1;
        $definitions = array();
        
        foreach($result as $rs) {
            
            if($current != $rs['name']) { // one time
                $ptr++;
                $definitions[$ptr] = new stdClass();
                
                $definitions[$ptr]->name          = $rs['name'];
                $definitions[$ptr]->pronuntiation = $rs['pronuntiation'];
                
                $current = $rs['name'];                
            }
            
            $definition = new stdClass();
            $definition->content     = $rs['content'];
            $definition->created     = $rs['created'];
            $definition->updated     = $rs['updated'];
            $definition->etymology   = $rs['etymology'];
            $definition->category_id = $rs['category_id']; 
            
            $definitions[$ptr]->definitions[] = $definition;            
        }
        
        // web-scrap definition from RAG dictionary if results are empty
        if(count($definitions) <= 0) {
            $rag = new Service_Model_RagDic();
            $result = $rag->query($q);
            
            if(!is_null($result)) {
                // Auto save after to scrap
                $this->autoSave($q, strip_tags($result, '<b><i>'));
                
                $definitions[0] = new stdClass();
                
                $definitions[0]->name          = $q;
                $definitions[0]->pronuntiation = '';
                
                $definition = new stdClass();
                $definition->content     = $result . '<cite>[Extraído do dicionario da RAG]</cite>';
                $definition->created     = date('Y-m-d H:i:s');
                $definition->updated     = date('Y-m-d H:i:s');
                $definition->etymology   = '';
                $definition->category_id = '';
                
                $definitions[0]->definitions[0] = $definition;
            } else {
                // Web scrap EDU Xunta
                $rag = new Service_Model_EduDic();
                $result = $rag->query($q);
                if(!is_null($result)) {
                    // Auto save after to scrap
                    $this->autoSave($q, strip_tags($result, '<b><i>'));
                    
                    $definitions[0] = new stdClass();
                    
                    $definitions[0]->name          = $q;
                    $definitions[0]->pronuntiation = '';
                    
                    $definition = new stdClass();
                    $definition->content     = $result . '<cite>[Extraído do dicionario edu.xunta.es]</cite>';
                    $definition->created     = date('Y-m-d H:i:s');
                    $definition->updated     = date('Y-m-d H:i:s');
                    $definition->etymology   = '';
                    $definition->category_id = '';
                    
                    $definitions[0]->definitions[0] = $definition;
                }
            }
        }
        
        return $definitions;
    }
    
    public function autoSave($q, $definition)
    {
        $term = new Admin_Model_DbTable_Terms();                
        
        $data = array();
        $data['name'] = $q;
        $data['pronuntiation'] = '';
        $data['created'] = date('Y-m-d H:i:s');
        $data['updated'] = date('Y-m-d H:i:s');
        
        $term_id = $term->insert($data);                
        
        // Save definition
        $definitions = new Admin_Model_DbTable_Definitions();
        
        unset($data['name']);
        unset($data['pronuntiation']);
        
        $data['content']     = $definition;
        $data['category_id'] = 0;
        $data['etymology']   = '';
        $data['term_id']     = $term_id;
        
        $definitions->insert($data);
    }
    
    public function terms2json()
    {                
        $sql = 'SELECT name FROM terms ORDER BY name';
        $result = $this->_db->fetchAll($sql);
        $dojoData= new Zend_Dojo_Data('name', $result, 'id');
        
        return $dojoData->toJson();
    }
    
    public function opensearch($q)
    {        
        $filter = new Zend_Filter();        
        $filter->addFilter(new Zend_Filter_StripTags())
               ->addFilter(new Zend_Filter_HtmlEntities())
               ->addFilter(new Zend_Filter_StringTrim());
        
        $q = $filter->filter($q);
        
        $output = '["'.$q.'", %s]';
        
        $sql = 'SELECT name FROM terms WHERE name LIKE "'.$q.'%" ORDER BY name';        
        $result = $this->_db->fetchAll($sql);
        
        $entries = array();
        foreach($result as $entry) {
            $entries[] = $filter->filter($entry['name']);
        }
        
        return sprintf($output, json_encode($entries));
    }
}